<?php 
	require('config.php');
	if (isset($_COOKIE['userid']) && $_COOKIE['userid'] != '')
	{
        $recType = $_POST['recType'];
        // 0 means personal, 1 means populatiry
        if ($recType == '0')
        {
            $stmt = $connection->prepare("select personalcurrentpos, personalnextpos from user_system_rec_pos where user_id=? limit 1");
        }
        else
        {
            $stmt = $connection->prepare("select popularcurrentpos, popularnextpos from user_system_rec_pos where user_id=? limit 1");
        }
        $stmt->bind_param("s", $_COOKIE['userid']);
    	$stmt->execute();
		$stmt->store_result();
		$row_cnt = $stmt->num_rows;
        $currentpos = 1;
        $nextpos = 1;
        //a new user
        if ($row_cnt == 0)
        {
            $stmt = $connection->prepare("insert into user_system_rec_pos (user_id) values (?)");
            $stmt->bind_param("s", $_COOKIE['userid']);
    	    $stmt->execute();
        }
        //a old user
        else
        {
            $stmt->bind_result($currentpos, $nextpos);
            $stmt->fetch();
        }
    	$time = date("Y-m-d H:i:s");
        //if user click refresh button
        if ($_POST['hrefs'])
        {
            //add user browsed
    		$hrefs = $_POST["hrefs"];
            if ($hrefs !==  '')
            {
                $start = 0;
                $pos = strpos($hrefs, ';');
                $length = $pos;
                $values = '';
                while ($pos !== false)
                {
                    $video_id = substr($hrefs, $start, $length);
                    $start = $pos + 1;
                    $pos = strpos($hrefs, ';', $start);
                    if ($values !== '')
                    {
                        $values = $values . ",";
                    }
                    $values = $values . "('". $_COOKIE['userid'] . "', '" . $video_id . "', '" . $time . "')";
                }
    		    $stmt = $connection->prepare("insert into user_browsed (user_id, video_id, browsed_time) values " . $values);
    		    $stmt->execute();
            }
            $currentpos = $nextpos;
        }
        $expiration = date("Y-m-d H:i:s", strtotime('-32 day'));
        //select all videos which have been watch by the user
        $stmt = $connection->prepare("select video_id from user_browsed where user_id=? and browsed_time>'" . $expiration  . "'");
        $stmt->bind_param("s", $_COOKIE['userid']);
    	$stmt->execute();
        $stmt->bind_result($video_id);
        $videos = array();
        while ($stmt->fetch())
        {
            array_push($videos, $video_id);
        }
        $videos = array_flip($videos);
        $stmt->close();
        if ($recType == '0')
        {
            $stmt = $connection->stmt_init();
            $stmt = $connection->prepare("select json from user_rec_list where user_id=? order by time desc limit 0,1");
            $stmt->bind_param("s", $_COOKIE['userid']);
    	    $stmt->execute();
            $stmt->bind_result($userlist);
            $userlist_array = Array();
            if ($stmt->fetch())
            {
                $stmt->fetch();
                $userlist_array = explode(' ', $userlist);
            }
            else
            {
                $memcached = new Memcached();
                $memcached->addServer('localhost', 11211);
		        $array = $memcached->get('pop_sorted');
                $size = sizeof($array);
                for ($i = 0; $i < $size; ++$i)
                {
                    array_push($userlist_array, $i);
                }
            }
        }
        $stmt = $connection->stmt_init();
        if ($recType == '0')
        {
		    echo getPersonalList($connection, $currentpos, $nextpos, $videos, $userlist_array);
        }
        else
        {
		    echo getPopularList($connection, $currentpos, $nextpos, $videos);
        }
		//echo getAnonymousList($connection, $currentpos, $nextpos, $videos, $userlist_array);
        updateUserPos($connection, $currentpos, $nextpos, $recType);
        $connection->close();
	}
	else
	{
        $t = 0;
        $s = array();
		echo getPopularList($connection, -1, $t, $s);
	}

    function updateUserPos($connection, $c, $n, $type)
    {
        if ($type == '0')
        {
            $stmt = $connection->prepare('update user_system_rec_pos set personalcurrentpos=?, personalnextpos=? where user_id=?');
        }
        else
        {
            $stmt = $connection->prepare('update user_system_rec_pos set popularcurrentpos=?, popularnextpos=? where user_id=?');
        }
        $stmt->bind_param('sss', $c, $n, $_COOKIE['userid']);
        $stmt->execute();
    }
	
	function getPersonalList(&$connection, $start, &$nextpos, $videos, $userlist)
	{
        $memcached = new Memcached();
        $memcached->addServer('localhost', 11211);
		$array = $memcached->get('pop_sorted');
        $size = sizeof($array);
        $addlist = 0;
        $line = $start;
		$result = '{"images":[';
		while ($addlist < 13)
		{
			if (abs($line) > $size)
			{
                $line = -1;
                continue;
			}
			$l = $array[$userlist[abs($line) - 1]];
            if ($line < 0 || !isset($videos[getVideoId($l)]))
            {
                if ($addlist < 12)
                {
			        $result = $result . $l . ',';
                }
                else
                {
			        $result = $result . $l. ']}';
                }
			    $addlist = $addlist + 1;
            }
            if ($line >= 0)
            {
			    $line++;
            }
            else
            {
                $line--;
            }
		}
        $nextpos = $line;
		return $result;
	}

	function getPopularList(&$connection, $start, &$nextpos, $videos)
	{
        $memcached = new Memcached();
        $memcached->addServer('localhost', 11211);
		$array = $memcached->get('pop_sorted');
        $size = sizeof($array);
        $addlist = 0;
        $line = $start;
		$result = '{"images":[';
		while ($addlist < 13)
		{
			if (abs($line) > $size)
			{
                $line = -1;
                continue;
			}
			$l = $array[abs($line) - 1];
            if ($line < 0 || !isset($videos[getVideoId($l)]))
            {
                if ($addlist < 12)
                {
			        $result = $result . $l . ',';
                }
                else
                {
			        $result = $result . $l. ']}';
                }
			    $addlist = $addlist + 1;
            }
            if ($line >= 0)
            {
			    $line++;
            }
            else
            {
                $line--;
            }
		}
        $nextpos = $line;
		return $result;
    }
	/*function getlist(&$connection, $start, &$nextpos, $videos)
	{
        $memcached = new Memcached();
        $memcached->addServer('localhost', 11211);
		$array = $memcached->get('pop_sorted');
        $size = sizeof($array);
        $addlist = 0;
        $line = $start;
		$result = '{"images":[';
		while ($addlist < 13)
		{
			if (abs($line) > $size)
			{
                $line = -1;
                continue;
			}
			$l = $array[abs($line) - 1];
            if ($line < 0 || !isset($videos[getVideoId($l)]))
            {
                if ($addlist < 12)
                {
			        $result = $result . $l . ',';
                }
                else
                {
			        $result = $result . $l. ']}';
                }
			    $addlist = $addlist + 1;
            }
            if ($line >= 0)
            {
			    $line++;
            }
            else
            {
                $line--;
            }
		}
        $nextpos = $line;
		return $result;
    }*/
    function getVideoId($s)
    {
        $start = strpos($s, "\"href\"") + 8;
        $end = strpos($s, "\"", $start);
        $out = substr($s, $start, $end - $start);
        return $out;
    }

?> 
